﻿using System;
using System.Collections.Generic;
using System.IO;
using WPS = Word;
namespace SubCom_Doc2Pdf
{
    internal class Doc2PdfViaWPS : Convertor
    {
        public Doc2PdfViaWPS(Target target) : base(target)
        {
            List<string> list = new List<string>();
            list.Add("WINWORD");
            list.Add("wps");
            SetTargetApps(list);   
        }

        protected override void OnProcess(Target target)
        {
            string src = target.Sources;
            string dest = target.Destination;

            WPS.Application WPSWord = new WPS.Application();
            WPSWord.DisplayAlerts = WPS.WdAlertLevel.wdAlertsNone;
            WPSWord.Visible = false;
            WPS.Document doc = null;
            try
            {
                doc = WPSWord.Documents.Open(@src, ReadOnly: false, Visible: true);
                doc.Activate();
                doc.ExportAsFixedFormat(@dest == null ? @src + ".pdf" : @dest,
                    WPS.WdExportFormat.wdExportFormatPDF, false,
                    WPS.WdExportOptimizeFor.wdExportOptimizeForOnScreen, WPS.WdExportRange.wdExportAllDocument,
                    0, 0, WPS.WdExportItem.wdExportDocumentContent, false, false,
                    WPS.WdExportCreateBookmarks.wdExportCreateWordBookmarks, false, true, false);
                Console.WriteLine(SUCCESS);
            }
            catch (Exception ex)
            {
                ThrowException(ex);
            }
            finally
            {
                try
                {
                    if (doc != null)
                        doc.Close(SaveChanges: false);
                }
                catch(Exception ex)
                {
                    ThrowException(ex);
                }
                WPSWord.Quit(SaveChanges: false);
            }
        }
    }
}